import React, { Component } from "react";
import { connect } from "react-redux";
import "styles/home/home.scss";
import { Icon } from "antd";
import { deepCopy, eventTrack, messages } from "share/common";
import EditTenantInfo from "containers/home/home-comp/edit-tenant-info";
import ShowInfo from "containers/home/home-comp/show-info";
import InPageStopAnnouncement from "components/template/in-page-stop-announcement/in-page-stop-announcement";
import homeService from "containers/home/home.service";
import MainCharts from "containers/home/home-comp/main-charts";
import Advertisement from "containers/home/home-comp/advertisement";
import UpdateLog from "containers/home/home-comp/update-log";
import HeliosNews from "containers/home/home-comp/helios-news";
import HeliosServiceCharts from "containers/home/home-comp/helios-service-charts.js";
import baseService from "share/base.service";
import MaskGuide from "components/template/main-init-modal-manage/mask-guide/mask-guide";
import { HOME_2_0 } from "components/template/main-init-modal-manage/mask-guide/mask-guide.modal";
import moment from "moment";
import bottomBannerImg from "images/home/bottom-banner.png";
import bottomBannerEnImg from "images/home/bottom-banner-en.jpg";

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showMaskGuide: false,
      cardData: {},
      openData: undefined,
      openLoading: false,
      HasOnlyOneChart: false,
    };
    this.refMap = {
      showBillNumStatisticsExp: "mainChartsRef",
      showCheckInvoiceExp: "CHECK_INVOICERef",
      showOcrExp: "OCRRef",
      showBweExp: "BWERef",
    };
  }

  componentWillMount() {
    this.getData();
    this.getOtherData();
  }

  componentDidMount() {
    this.handleGuide();
  }

  componentWillUnmount() {}

  handleGuide = () => {
    const { tenant } = this.props;
    const oldTenant = !moment("2020-12-18").isBefore(moment(tenant.createdDate));
    const initDone = sessionStorage.getItem("hly.init.done");
    if (!oldTenant) return; //2020-12-18 迭代后的租户 管理员首页不引导
    const finishedGuide = localStorage.getItem("hly.guide") ? JSON.parse(localStorage.getItem("hly.guide")) : [];
    if (finishedGuide.indexOf("NEW_HOME_GUIDE") > -1) return;
    if (!initDone) {
      sessionStorage.setItem("hly.un-guide", "NEW_HOME_GUIDE");
      return;
    } //初始化 7层 引导没有走完
    this.setState({ showMaskGuide: true }, () => {
      finishedGuide.push("NEW_HOME_GUIDE");
      localStorage.setItem("hly.guide", JSON.stringify([...finishedGuide]));
    });
  };

  handleMaskResize = () => {
    this.setState({ showMaskGuide: false }, () => {
      setTimeout(() => {
        this.setState({ showMaskGuide: true });
      }, 300);
    });
  };

  getData = () => {
    homeService
      .getData()
      .then((res) => {
        this.setState({ cardData: res.data });
      })
      .catch();
  };

  getOtherData = () => {
    this.setState({ openLoading: true });
    homeService.getOpenServiceData().then((res) => {
      if (res.status === 200) {
        this.setState({ openData: res.data });
      }
    });
  };

  hideExample = (key) => {
    const { userOtherSetting } = this.props.user;
    userOtherSetting[key] = false;
    homeService.setExampleStatus(userOtherSetting).then((res) => {
      this[this.refMap[key]] && this[this.refMap[key]].setLoading();
      baseService.getUser().then(() => {
        this[this.refMap[key]] && this[this.refMap[key]].getRealData();
      });
    });
  };

  handleHasOnly = () => {
    this.setState({ HasOnlyOneChart: true });
  };

  doSurvey = () => {
    const { tenant, user } = this.props;
    const currentDomain = location.host;
    const map = {
      "106.15.26.10:10080": "dev",
      "uat.huilianyi.com": "uat",
      "stage.huilianyi.com": "stage",
      "stage9084.huilianyi.com": "stage9084",
      "consolehelios.huilianyi.com": "prodPre",
      "localhost:8000": "localEnvironment",
    };
    let environment = "prod";
    Object.keys(map).find((domain) => {
      if (currentDomain.indexOf(domain) !== -1) {
        environment = map[domain];
        return true;
      }
    });
    const target = encodeURIComponent(
      `environment=${environment};source=pcAdmin;tenantId=${tenant.id};userId=${user.id}`
    );
    window.open(`https://wj.qq.com/s2/7721954/1fd2/?openid=${target}`, "_blank");
    eventTrack({
      category: "1218-新首页-埋点",
      action: "用户主动点了满意度调查",
      label: tenant.tenantName,
    });
  };

  render() {
    const { isDingTalkEnv, tenant, language, user, menuTree } = this.props;
    const { cardData, openData, HasOnlyOneChart, showMaskGuide } = this.state;
    const { userOtherSetting = {} } = user;
    const { showBillNumStatisticsExp, showCheckInvoiceExp, showOcrExp, showBweExp } = userOtherSetting;
    const trialTenant = !["REAL"].includes(tenant.licenseType); //除正式外的 所以其他类型 ）租户(试用/内部测试)

    return (
      <div className="home full-height-page-88 full-page-margin" id={"home-scroll-container"}>
        <div className={"home-head-box"} id={"home-head-box-guide-id"}>
          <div className="max-wrapper">
            <InPageStopAnnouncement />
            <div className="title-and-switch">
              <div className="home-title">{messages("basic-1.key278") /*管理员首页*/}</div>
              <div className="edit-button-group">
                {menuTree.keyUrl.dashboard && (
                  <div
                    className="page-change-url"
                    onClick={() => {
                      this.context.router.push("/main/dashboard");
                      sessionStorage.setItem("hly.tempHome", "dashboard");
                    }}
                  >
                    <Icon type="swap" />
                    <span>&nbsp;{messages("basic-1.key47") /*切换到个人首页*/}</span>
                  </div>
                )}
                <div
                  className="page-change-url"
                  onClick={this.editTenantInfoRef && this.editTenantInfoRef.showSetModal}
                >
                  <Icon type="edit" />
                  <span>&nbsp;{messages("basic-1.key48") /*编辑企业信息*/}</span>
                </div>
              </div>
            </div>
            <ShowInfo cardData={cardData} tenant={tenant} isDingTalkEnv={isDingTalkEnv} />
          </div>
        </div>
        <div className={"home-content"}>
          <div className={`max-content ${HasOnlyOneChart ? "one-chart" : ""}`}>
            <MainCharts
              tenant={tenant}
              hasOnly={this.handleHasOnly}
              onRef={(ref) => (this.mainChartsRef = ref)}
              trialTenant={trialTenant && showBillNumStatisticsExp}
              openData={openData}
              onConfirm={() => {
                this.hideExample("showBillNumStatisticsExp");
              }}
            />
            <Advertisement route={this.props.route} tenant={tenant} language={language} />
            <UpdateLog tenant={tenant} />
            <HeliosNews tenant={tenant} />
            <div>
              <HeliosServiceCharts
                tenant={tenant}
                isDingTalkEnv={isDingTalkEnv}
                onRef={(ref) => (this.CHECK_INVOICERef = ref)}
                trialTenant={trialTenant && showCheckInvoiceExp}
                openData={openData}
                cardData={cardData}
                type={"CHECK_INVOICE"}
                onConfirm={() => {
                  this.hideExample("showCheckInvoiceExp");
                }}
              />
              <HeliosServiceCharts
                tenant={tenant}
                isDingTalkEnv={isDingTalkEnv}
                onRef={(ref) => (this.OCRRef = ref)}
                trialTenant={trialTenant && showOcrExp}
                openData={openData}
                cardData={cardData}
                type={"OCR"}
                onConfirm={() => {
                  this.hideExample("showOcrExp");
                }}
              />
              <HeliosServiceCharts
                tenant={tenant}
                isDingTalkEnv={isDingTalkEnv}
                onRef={(ref) => (this.BWERef = ref)}
                trialTenant={trialTenant && showBweExp}
                openData={openData}
                cardData={cardData}
                type={"BWE"}
                onConfirm={() => {
                  this.hideExample("showBweExp");
                }}
              />
            </div>
            <div style={{ clear: "both" }} />
            <div
              onClick={this.doSurvey}
              style={{ backgroundImage: `url('${language.code === "zh_cn" ? bottomBannerImg : bottomBannerEnImg}')` }}
              className="bottom-banner"
            />
          </div>
        </div>
        <EditTenantInfo onRef={(ref) => (this.editTenantInfoRef = ref)} />
        {showMaskGuide && (
          <MaskGuide
            config={deepCopy(HOME_2_0)}
            onResize={this.handleMaskResize}
            onClose={() => {
              this.setState({ showMaskGuide: false });
              eventTrack({
                category: "1218-新首页-埋点",
                action: "完成了管理员首页引导",
                label: tenant.tenantName,
              });
            }}
          />
        )}
      </div>
    );
  }
}

Home.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company,
    language: state.main.language,
    tenant: state.login.tenant,
    isOldCompany: state.login.isOldCompany,
    menuTree: state.login.menuTree,
    isDingTalkEnv: state.main.isDingTalkEnv,
  };
}

export default connect(mapStateToProps)(Home);
